package com.growthsee.rider.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.growthsee.common.core.domain.AjaxResult;
import com.growthsee.rider.domain.RiderCarsInfo;
import com.growthsee.rider.domain.RiderLoanInfo;
import com.growthsee.rider.domain.RiderLoanInfoExt;
import com.growthsee.rider.domain.RiderPackage;
import com.growthsee.rider.domain.dto.RiderLoanInfoDto;
import com.growthsee.rider.mapper.RiderLoanInfoExtMapper;
import com.growthsee.rider.mapper.RiderLoanInfoMapper;
import com.growthsee.rider.service.RiderCarsInfoService;
import com.growthsee.rider.service.RiderLoanInfoService;
import com.growthsee.rider.service.RiderPackageService;
import com.growthsee.rider.utils.BasicPathUtil;
import com.growthsee.rider.utils.SM.SM2Utils;
import lombok.AllArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 借款信息 服务实现类
 * </p>
 *
 * @author csy
 * @since 2021-05-25
 */
@Service
@AllArgsConstructor
public class RiderLoanInfoServiceImpl extends ServiceImpl<RiderLoanInfoMapper, RiderLoanInfo> implements RiderLoanInfoService {

    private final RiderCarsInfoService riderCarsInfoService;
    private final RiderPackageService packageService;
    private final RiderLoanInfoExtMapper riderLoanInfoExtMapper;

    @Override
    public AjaxResult syncLoan(String loanInfo) {
        if(StringUtils.isEmpty(loanInfo))return AjaxResult.error("请传入借款信息");
        //SM2解密
        try {
            System.out.println("传入购车信息"+loanInfo);
            String decrypt = SM2Utils.decrypt(BasicPathUtil.getSystemPrik(), loanInfo);
            ObjectMapper mapper = new ObjectMapper();
            RiderLoanInfoDto riderLoanInfoDto = mapper.readValue(decrypt , RiderLoanInfoDto.class);
            riderLoanInfoDto.setStr(loanInfo);
            if(Objects.isNull(riderLoanInfoDto) || StringUtils.isEmpty(riderLoanInfoDto.getIdCardNo()))return AjaxResult.error("idCardNo必填字段");
            RiderLoanInfo riderLoanInfo = baseMapper.selectOne(Wrappers.<RiderLoanInfo>lambdaQuery().eq(RiderLoanInfo::getIdCardNo, riderLoanInfoDto.getIdCardNo()));
            if(Objects.isNull(riderLoanInfo)){
                riderLoanInfoDto.setCreateTime(new Date());
                RiderLoanInfoExt loanInfoExt = new RiderLoanInfoExt();
                baseMapper.insert(riderLoanInfoDto);
                loanInfoExt.setLoanId(riderLoanInfoDto.getId());
                loanInfoExt.setStr(riderLoanInfoDto.getStr());
                riderLoanInfoExtMapper.insert(loanInfoExt);
                return save(riderLoanInfoDto);
            }else {
                LambdaQueryWrapper<RiderLoanInfo> queryWrapper = Wrappers.<RiderLoanInfo>lambdaQuery().eq(RiderLoanInfo::getIdCardNo, riderLoanInfoDto.getIdCardNo());
                RiderLoanInfo info = baseMapper.selectOne(queryWrapper);
                RiderLoanInfo source = new RiderLoanInfo();
                source.setId(info.getId());
                riderLoanInfoDto.setId(info.getId());
                source.setUpdateTime(new Date());
                if(StringUtils.isNotEmpty(riderLoanInfoDto.getAcctCard())){
                    source.setAcctCard(riderLoanInfoDto.getAcctCard());
                }
                if(StringUtils.isNotEmpty(riderLoanInfoDto.getUserName())){
                    source.setUserName(riderLoanInfoDto.getUserName());
                }
                if(!Objects.isNull(riderLoanInfoDto.getBuyTime())){
                    source.setBuyTime(riderLoanInfoDto.getBuyTime());
                }
                if(!Objects.isNull(riderLoanInfoDto.getStat())){
                    source.setStat(riderLoanInfoDto.getStat());
                }
                if(!Objects.isNull(riderLoanInfoDto.getCreditStat())){
                    source.setCreditStat(riderLoanInfoDto.getCreditStat());
                }
                if(!Objects.isNull(riderLoanInfoDto.getLoanStat())){
                    source.setLoanStat(riderLoanInfoDto.getLoanStat());
                }
                if(!Objects.isNull(riderLoanInfoDto.getTotalAmt())){
                    source.setLoanDate(riderLoanInfoDto.getLoanDate());
                }
                if(!Objects.isNull(riderLoanInfoDto.getLoanPeriods())){
                    source.setLoanPeriods(riderLoanInfoDto.getLoanPeriods());
                }
                if(!Objects.isNull(riderLoanInfoDto.getNoClearPeriods())){
                    source.setNoClearPeriods(riderLoanInfoDto.getNoClearPeriods());
                }
                if(StringUtils.isNotEmpty(riderLoanInfoDto.getChannelMerName())){
                    source.setChannelMerName(riderLoanInfoDto.getChannelMerName());
                }
                if(StringUtils.isNotEmpty(riderLoanInfoDto.getLoanNos())){
                    source.setLoanNos(riderLoanInfoDto.getLoanNos());
                }
                baseMapper.updateById(source);
                exclude(riderLoanInfoDto);
                save(riderLoanInfoDto);
            }
            return AjaxResult.success();
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("解密失败");
        }
    }

    @Override
    public AjaxResult analysis(String loanInfo) {
        try {
            String decrypt = SM2Utils.decrypt(BasicPathUtil.getSystemPrik(), loanInfo);
            ObjectMapper mapper = new ObjectMapper();
            RiderLoanInfoDto riderLoanInfoDto = mapper.readValue(decrypt , RiderLoanInfoDto.class);
            return AjaxResult.success(riderLoanInfoDto);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public AjaxResult handler() {
        List<RiderLoanInfoExt>extList = riderLoanInfoExtMapper.selectList(Wrappers.lambdaQuery());
        Optional.ofNullable(extList).ifPresent(v->{
            extList.removeIf(f->StringUtils.isEmpty(f.getStr()));
            List<String>loanIds = extList.stream().map(s->s.getLoanId()).distinct().collect(Collectors.toList());
            baseMapper.delete(Wrappers.<RiderLoanInfo>lambdaQuery().in(RiderLoanInfo::getId,loanIds));
            v.forEach(t->{
                syncLoan(t.getStr());
            });
        });
        return AjaxResult.success();
    }

    /**
     * 保存套餐和购车信息
     * @param riderLoanInfoDto
     * @return
     */
    private AjaxResult save(RiderLoanInfoDto riderLoanInfoDto){

        if(CollectionUtils.isNotEmpty(riderLoanInfoDto.getBuyCarsInfo())){
            for (RiderCarsInfo info : riderLoanInfoDto.getBuyCarsInfo()) {
                info.setLoanId(riderLoanInfoDto.getId());
            }
            riderCarsInfoService.saveBatch(riderLoanInfoDto.getBuyCarsInfo());
        }
        if(CollectionUtils.isNotEmpty(riderLoanInfoDto.getRiderPackages())){
            for (RiderPackage riderPackage : riderLoanInfoDto.getRiderPackages()) {
                riderPackage.setLoanId(riderLoanInfoDto.getId());
            }
            packageService.saveBatch(riderLoanInfoDto.getRiderPackages());
        }
        return AjaxResult.success();
    }

    /**
     * 排除已近存在的套餐和购车信息
     * @param riderLoanInfoDto
     */
    private void exclude(RiderLoanInfoDto riderLoanInfoDto){
        if(CollectionUtils.isNotEmpty(riderLoanInfoDto.getBuyCarsInfo())){
            List<RiderCarsInfo> list = riderCarsInfoService.list(Wrappers.<RiderCarsInfo>lambdaQuery().eq(RiderCarsInfo::getLoanId, riderLoanInfoDto.getId()));
            if(CollectionUtils.isNotEmpty(list)){
                riderCarsInfoService.remove(Wrappers.<RiderCarsInfo>lambdaQuery().eq(RiderCarsInfo::getLoanId,riderLoanInfoDto.getId()));
            }
            if(CollectionUtils.isNotEmpty(riderLoanInfoDto.getRiderPackages())){
                List<RiderPackage> packages = packageService.list(Wrappers.<RiderPackage>lambdaQuery().eq(RiderPackage::getLoanId, riderLoanInfoDto.getId()));
                if(CollectionUtils.isNotEmpty(packages)){
                    packageService.remove(Wrappers.<RiderPackage>lambdaQuery().eq(RiderPackage::getLoanId,riderLoanInfoDto.getId()));
                }
            }

        }
        //查询购车信息
    }
}
